/*
 * Miya.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.miya.cloud.erpdemo;

import com.miya.erpmofa.common.lang.request.single.*;
import com.miya.erpmofa.common.lang.response.commodity.single.CommodityInfo;
import com.miya.erpmofa.common.lang.response.commodity.single.PromoteInfo;
import com.miya.erpmofa.common.lang.response.member.MemberInfo;
import com.miya.erpmofa.common.lang.response.order.OrderInfo;
import com.miya.erpmofa.common.lang.response.promote.single.PromoteRstInfo;
import com.miya.erpmofa.common.lang.response.ticket.TicketInfo;
import com.miya.erpmofa.common.lang.result.Result;
import com.miya.erpmofa.common.lang.sign.MiyaApiException;
import com.miya.erpmofa.common.lang.sign.MiyaSignature;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author ${zhaowei}
 * @version $Id: DemoController.java, v 0.1 2018年08月03日 14:55 ${zhaowei} Exp $
 */
@RestController
public class DemoController {
    /**
     米雅公钥,用来验证签名
     */
    private String miyaPublickKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI4B+hgBP4bO7B7jTGVnQjQVwuk8VD7rVCvqhh2QK0RCCug63f/jaJnJMLWFOOkjgxIUev+aRAPneQWfDUOG5E5OHjKBsx8IKGx131konm7RShtqM6y+mWN4Tk/cBx6XvMGLWbnWlurWOcvvMFG75V44vAkLy0lECKeP+0QajI8wIDAQAB";
    /**
     应用私钥,用来加签
     */
    private String appPrivateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMjgH6GAE/hs7sHuNMZWdCNBXC6TxUPutUK+qGHZArREIK6Drd/+NomckwtYU46SODEhR6/5pEA+d5BZ8NQ4bkTk4eMoGzHwgobHXfWSiebtFKG2ozrL6ZY3hOT9wHHpe8wYtZudaW6tY5y+8wUbvlXji8CQvLSUQIp4/7RBqMjzAgMBAAECgYBvr10m2CVCXJ6rKJwjInJUH8T3CKYHTTNutr68GIJOZAqfvQrxnVAJVwrSpftfK6Eef9hx2SUfqxujIL6r3+w+WXdYPubP+K8WQwZ6a/FY6m6Puih9FEB3kXp1d8Sqxykt4B5DWzzwspegD//p9t/X0nBM4B9npQEqh66XnLZccQJBAOyRWaiFrqBT50aGEq2GqFJInKAz5qviBqkdAQCLfAZbtQlpFSkzNP2/t0X0I50YrQ38nkUExY3oMco9SjJR418CQQDZYDhoI5t08mSHgzBtL2M5TIR/3Ck4rbt3hCCBnGqHKP3FvVUcAouUhN3YbpaxvSX5CabaOXW7PELef2w+JPbtAkEAkzl6BOj9XoYY/sjdwuR0yJCr+P+T5RCLeJ+2SfKEwyg7qJmfM77MkcbIdl6T82ax/GxkyytHDyOcKPKvxFU2HQJBAMz/VhK3ycp/MVku2kON1ghaZfZivSkrhkjO/QzeYwQ2HyUVSadRqyqUJtcOa+UQ2TfD52uTlrjNus4z4vO0Tn0CQQCkHF9oFZNdfMWahLn7Gq2rNjEL0YSDWNCd/S32hOZTeoOrTMr14WZpWnN8+3bg2oLfE5Rqr9pYlOILkaoHnQPh=";
    /**
     app_id,米雅分配给开发者的应用ID，开发者在米雅开放平台创建应用时候生成, 仅用于参数校验
     */
    private String appId = "20283923";
    /**
     merchant_id,米雅分配给开发者的商户ID，开发者在米雅开放平台申请,  仅用于参数校验
     */
    private String merchantId = "20283923232";
    /**
     store_id, erp定义的门店编号
     */
    private String storeId = "28e92382";

    /**
     commodityList, 测试用，有效商品编号list
     */
    private String[] commodityList = new String[]{"6914068017563","6914068017565"};

    private String checkParameter(Map<String, String> paramMap) {
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            String tmpKey = entry.getKey();
            String tmpValue = entry.getValue();
            if (tmpValue == null || tmpValue.isEmpty()) {
                return tmpKey;
            }
        }
        return null;
    }


    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 商品查询
     */
    @PostMapping("/commodity/query")
    public Result<List<CommodityInfo>> commodityQuery(@RequestBody CommodityQueryRequest commodityQueryRequest){
        boolean flag = false;
        Result result = new Result();
        result.setSuccess(false);

        // 验证签名
        try {
            flag = MiyaSignature.rsaCheck(commodityQueryRequest.initSignContent(),commodityQueryRequest.getSign(), miyaPublickKey, commodityQueryRequest.getCharset(),
                    commodityQueryRequest.getSign_type());
        } catch (MiyaApiException e) {
            e.printStackTrace();
            result.setErr_code("sign_err");
            result.setErr_msg("验签失败");
        }

        if(!flag){
            result.setErr_code("sign_err");
            result.setErr_msg("验签失败");
            return result;
        }

        // 请求参数解析
        String tmpTimestamp = commodityQueryRequest.getTimestamp();
        String tmpAppId = commodityQueryRequest.getApp_id();
        String tmpMerchantId = commodityQueryRequest.getMerchant_id();
        String tmpFormat = commodityQueryRequest.getFormat();
        String tmpCharset = commodityQueryRequest.getCharset();
        String tmpSignType = commodityQueryRequest.getSign_type();
        String tmpStoreId = commodityQueryRequest.getStore_id();
        String tmpVersion = commodityQueryRequest.getVersion();
        String tmpDeviceNo = commodityQueryRequest.getDevice_no();
        String tmpCurrencyCode = commodityQueryRequest.getCurrency_code();
        String tmpCode = commodityQueryRequest.getCode();

        Map<String, String> tmpParameterMap = new HashMap<>(7);
        tmpParameterMap.put("timestamp", tmpTimestamp);
        tmpParameterMap.put("format", tmpFormat);
        tmpParameterMap.put("charset", tmpCharset);
        tmpParameterMap.put("sign_type", tmpSignType);
        tmpParameterMap.put("version", tmpVersion);
        tmpParameterMap.put("device_no", tmpDeviceNo);
        tmpParameterMap.put("currency_code", tmpCurrencyCode);

        // 验证必填字段
        String cr = checkParameter(tmpParameterMap);
        if (cr != null) {
            result.setErr_code("parameter_verify_fail");
            result.setErr_msg(String.format("参数校验失败，%s参数不能为空", cr));
            return result;
        }

        // 验证appId字段
        if (!tmpAppId.equals(appId)) {
            result.setErr_code("app_id_not_exist");
            result.setErr_msg("app_id不存在");
            return result;
        }

        //验证merchantId字段
        if (!tmpMerchantId.equals(merchantId)) {
            result.setErr_code("merchant_id_not_exist");
            result.setErr_msg("merchant_id不存在");
            return result;
        }

        //验证storeId字段
        if (!tmpStoreId.equals(storeId)) {
            result.setErr_code("store_id_not_exist");
            result.setErr_msg("store_id不存在");
            return result;
        }

        //验证code字段
        boolean isContains = Arrays.asList(commodityList).contains(tmpCode);
        if (!isContains) {
            result.setErr_code("commodity_not_exist");
            result.setSuccess(false);
            result.setErr_msg("查询商品不存在");
            return result;
        }


        CommodityInfo commodityInfo = DataGenerator.commodityInfoData(tmpCode);
        result.setSuccess(true);
        result.setResultObj(commodityInfo);
        return result;
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 会员查询
     */
    @PostMapping("/member/query")
    public Result<List<MemberInfo>> memberQuery(@RequestBody MemberQueryRequest memberQueryRequest){
        boolean flag = false;
        Result result = new Result();
        result.setSuccess(false);

        // 验证签名
        try {
            flag = MiyaSignature.rsaCheck(memberQueryRequest.initSignContent(),memberQueryRequest.getSign(), miyaPublickKey, memberQueryRequest.getCharset(),
                    memberQueryRequest.getSign_type());
        } catch (MiyaApiException e) {
            e.printStackTrace();
        }

        if(!flag){
            result.setErr_code("sign_err");
            result.setErr_msg("验签失败");
            return result;
        }

        // 请求参数解析
        String tmpTimestamp = memberQueryRequest.getTimestamp();
        String tmpAppId = memberQueryRequest.getApp_id();
        String tmpMerchantId = memberQueryRequest.getMerchant_id();
        String tmpFormat = memberQueryRequest.getFormat();
        String tmpCharset = memberQueryRequest.getCharset();
        String tmpSignType = memberQueryRequest.getSign_type();
        String tmpStoreId = memberQueryRequest.getStore_id();
        String tmpVersion = memberQueryRequest.getVersion();
        String tmpDeviceNo = memberQueryRequest.getDevice_no();
        String tmpCurrencyCode = memberQueryRequest.getCurrency_code();
        String tmpCardNo = memberQueryRequest.getCard_no();
        String tmpPhoneNo = memberQueryRequest.getPhone_no();
        String tmpIdCard = memberQueryRequest.getId_card();

        Map<String, String> tmpParameterMap = new HashMap<>(10);
        tmpParameterMap.put("timestamp", tmpTimestamp);
        tmpParameterMap.put("format", tmpFormat);
        tmpParameterMap.put("charset", tmpCharset);
        tmpParameterMap.put("sign_type", tmpSignType);
        tmpParameterMap.put("version", tmpVersion);
        tmpParameterMap.put("device_no", tmpDeviceNo);
        tmpParameterMap.put("currency_code", tmpCurrencyCode);

        // 验证必填字段
        String cr = checkParameter(tmpParameterMap);
        if (cr != null) {
            result.setErr_code("parameter_verify_fail");
            result.setErr_msg(String.format("参数校验失败，%s参数不能为空", cr));
            return result;
        }

        if (!(tmpCardNo == null && tmpPhoneNo == null && tmpIdCard == null)) {
            result.setErr_code("parameter_verify_fail");
            result.setErr_msg(String.format("参数校验失败，card_no/phone_no/id_card参数不能为空"));
        }

        // 验证appId字段
        if (!tmpAppId.equals(appId)) {
            result.setErr_code("app_id_not_exist");
            result.setErr_msg("app_id不存在");
            return result;
        }

        //验证merchantId字段
        if (!tmpMerchantId.equals(merchantId)) {
            result.setErr_code("merchant_id_not_exist");
            result.setErr_msg("merchant_id不存在");
            return result;
        }

        //验证storeId字段
        if (!tmpStoreId.equals(storeId)) {
            result.setErr_code("store_id_not_exist");
            result.setErr_msg("store_id不存在");
            return result;
        }

        MemberInfo memberInfo = DataGenerator.memberInfoData(tmpCardNo);
        result.setSuccess(true);
        result.setResultObj(memberInfo);
        return result;
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 促销计算
     */
    @PostMapping("/promote/calc")
    public Result<List<PromoteInfo>> memberQuery(@RequestBody PromoteCalcRequest promoteCalcRequest){
        boolean flag = false;
        Result result = new Result();
        result.setSuccess(false);

        // 验证签名
        try {
            flag = MiyaSignature.rsaCheck(promoteCalcRequest.initSignContent(),promoteCalcRequest.getSign(), miyaPublickKey, promoteCalcRequest.getCharset(),
                    promoteCalcRequest.getSign_type());
        } catch (MiyaApiException e) {
            e.printStackTrace();
        }

        if(!flag){
            result.setErr_code("sign_err");
            result.setErr_msg("验签失败");
            return result;
        }

        // 请求参数解析
        String tmpTimestamp = promoteCalcRequest.getTimestamp();
        String tmpAppId = promoteCalcRequest.getApp_id();
        String tmpMerchantId = promoteCalcRequest.getMerchant_id();
        String tmpFormat = promoteCalcRequest.getFormat();
        String tmpCharset = promoteCalcRequest.getCharset();
        String tmpSignType = promoteCalcRequest.getSign_type();
        String tmpStoreId = promoteCalcRequest.getStore_id();
        String tmpVersion = promoteCalcRequest.getVersion();
        String tmpDeviceNo = promoteCalcRequest.getDevice_no();
        String tmpCurrencyCode = promoteCalcRequest.getCurrency_code();
        List<PromoteCommodityItem> pciList = promoteCalcRequest.getCommodity_list();

        Map<String, String> tmpParameterMap = new HashMap<>(10);
        tmpParameterMap.put("timestamp", tmpTimestamp);
        tmpParameterMap.put("format", tmpFormat);
        tmpParameterMap.put("charset", tmpCharset);
        tmpParameterMap.put("sign_type", tmpSignType);
        tmpParameterMap.put("version", tmpVersion);
        tmpParameterMap.put("device_no", tmpDeviceNo);
        tmpParameterMap.put("currency_code", tmpCurrencyCode);

        // 验证必填字段
        String cr = checkParameter(tmpParameterMap);
        if (cr != null) {
            result.setErr_code("parameter_verify_fail");
            result.setErr_msg(String.format("参数校验失败，%s参数不能为空", cr));
            return result;
        }

        for (Iterator iter = pciList.iterator(); iter.hasNext();) {
            PromoteCommodityItem pci = (PromoteCommodityItem)iter.next();
            String tmpBarcode = pci.getBarcode();
            if (tmpBarcode == null || tmpBarcode.isEmpty()) {
                result.setErr_code("parameter_verify_fail");
                result.setErr_msg("参数校验失败，barcode参数不能为空");
                return result;
            }

            Integer tmpQuantity = pci.getQuantity();
            if (tmpQuantity == null || tmpQuantity.equals(0)) {
                result.setErr_code("parameter_verify_fail");
                result.setErr_msg("参数校验失败，quantity参数不能为空");
                return result;
            }
        }

        // 验证appId字段
        if (!tmpAppId.equals(appId)) {
            result.setErr_code("app_id_not_exist");
            result.setErr_msg("app_id不存在");
            return result;
        }

        //验证merchantId字段
        if (!tmpMerchantId.equals(merchantId)) {
            result.setErr_code("merchant_id_not_exist");
            result.setErr_msg("merchant_id不存在");
            return result;
        }

        //验证storeId字段
        if (!tmpStoreId.equals(storeId)) {
            result.setErr_code("store_id_not_exist");
            result.setErr_msg("store_id不存在");
            return result;
        }

        PromoteRstInfo promoteRstInfo = DataGenerator.promoteRstInfoData(pciList);
        result.setSuccess(true);
        result.setResultObj(promoteRstInfo);
        return result;
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 获取订单号小票号
     */
    @PostMapping("/ticket/query")
    public Result<List<TicketInfo>> memberQuery(@RequestBody TicketQueryRequest ticketQueryRequest){
        boolean flag = false;
        Result result = new Result();
        result.setSuccess(false);

        // 验证签名
        try {
            flag = MiyaSignature.rsaCheck(ticketQueryRequest.initSignContent(),ticketQueryRequest.getSign(), miyaPublickKey, ticketQueryRequest.getCharset(),
                    ticketQueryRequest.getSign_type());
        } catch (MiyaApiException e) {
            e.printStackTrace();
        }

        if(!flag){
            result.setErr_code("sign_err");
            result.setErr_msg("验签失败");
            return result;
        }

        // 请求参数解析
        String tmpTimestamp = ticketQueryRequest.getTimestamp();
        String tmpAppId = ticketQueryRequest.getApp_id();
        String tmpMerchantId = ticketQueryRequest.getMerchant_id();
        String tmpFormat = ticketQueryRequest.getFormat();
        String tmpCharset = ticketQueryRequest.getCharset();
        String tmpSignType = ticketQueryRequest.getSign_type();
        String tmpStoreId = ticketQueryRequest.getStore_id();
        String tmpVersion = ticketQueryRequest.getVersion();
        String tmpDeviceNo = ticketQueryRequest.getDevice_no();
        String tmpCurrencyCode = ticketQueryRequest.getCurrency_code();

        Map<String, String> tmpParameterMap = new HashMap<>(10);
        tmpParameterMap.put("timestamp", tmpTimestamp);
        tmpParameterMap.put("format", tmpFormat);
        tmpParameterMap.put("charset", tmpCharset);
        tmpParameterMap.put("sign_type", tmpSignType);
        tmpParameterMap.put("version", tmpVersion);
        tmpParameterMap.put("device_no", tmpDeviceNo);
        tmpParameterMap.put("currency_code", tmpCurrencyCode);

        // 验证必填字段
        String cr = checkParameter(tmpParameterMap);
        if (cr != null) {
            result.setErr_code("parameter_verify_fail");
            result.setErr_msg(String.format("参数校验失败，%s参数不能为空", cr));
            return result;
        }

        // 验证appId字段
        if (!tmpAppId.equals(appId)) {
            result.setErr_code("app_id_not_exist");
            result.setErr_msg("app_id不存在");
            return result;
        }

        //验证merchantId字段
        if (!tmpMerchantId.equals(merchantId)) {
            result.setErr_code("merchant_id_not_exist");
            result.setErr_msg("merchant_id不存在");
            return result;
        }

        //验证storeId字段
        if (!tmpStoreId.equals(storeId)) {
            result.setErr_code("store_id_not_exist");
            result.setErr_msg("store_id不存在");
            return result;
        }
        TicketInfo ticketInfo = DataGenerator.ticketInfoData();
        result.setSuccess(true);
        result.setResultObj(ticketInfo);
        return result;
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 订单回调
     */
    @PostMapping("/order/writeBack")
    public Result<List<OrderInfo>> memberQuery(@RequestBody OrderWriteBackRequest orderWriteBackRequest){
        boolean flag = false;
        Result result = new Result();
        result.setSuccess(false);

        // 验证签名
        try {
            flag = MiyaSignature.rsaCheck(orderWriteBackRequest.initSignContent(),orderWriteBackRequest.getSign(), miyaPublickKey, orderWriteBackRequest.getCharset(),
                    orderWriteBackRequest.getSign_type());
        } catch (MiyaApiException e) {
            e.printStackTrace();
        }

        if(!flag){
            result.setErr_code("sign_err");
            result.setErr_msg("验签失败");
            return result;
        }

        // 请求参数解析
        String tmpTimestamp = orderWriteBackRequest.getTimestamp();
        String tmpAppId = orderWriteBackRequest.getApp_id();
        String tmpMerchantId = orderWriteBackRequest.getMerchant_id();
        String tmpFormat = orderWriteBackRequest.getFormat();
        String tmpCharset = orderWriteBackRequest.getCharset();
        String tmpSignType = orderWriteBackRequest.getSign_type();
        String tmpStoreId = orderWriteBackRequest.getStore_id();
        String tmpVersion = orderWriteBackRequest.getVersion();
        String tmpDeviceNo = orderWriteBackRequest.getDevice_no();
        String tmpCurrencyCode = orderWriteBackRequest.getCurrency_code();
        String tmpOutBizNo = orderWriteBackRequest.getOut_biz_no();
        List<PayItem> payItemList = orderWriteBackRequest.getPay_list();


        Map<String, String> tmpParameterMap = new HashMap<>(10);
        tmpParameterMap.put("timestamp", tmpTimestamp);
        tmpParameterMap.put("format", tmpFormat);
        tmpParameterMap.put("charset", tmpCharset);
        tmpParameterMap.put("sign_type", tmpSignType);
        tmpParameterMap.put("version", tmpVersion);
        tmpParameterMap.put("device_no", tmpDeviceNo);
        tmpParameterMap.put("currency_code", tmpCurrencyCode);
        tmpParameterMap.put("out_biz_no", tmpOutBizNo);

        // 验证必填字段
        String cr = checkParameter(tmpParameterMap);
        if (cr != null) {
            result.setErr_code("parameter_verify_fail");
            result.setErr_msg(String.format("参数校验失败，%s参数不能为空", cr));
            return result;
        }

        // 验证appId字段
        if (!tmpAppId.equals(appId)) {
            result.setErr_code("app_id_not_exist");
            result.setErr_msg("app_id不存在");
            return result;
        }

        //验证merchantId字段
        if (!tmpMerchantId.equals(merchantId)) {
            result.setErr_code("merchant_id_not_exist");
            result.setErr_msg("merchant_id不存在");
            return result;
        }

        //验证storeId字段
        if (!tmpStoreId.equals(storeId)) {
            result.setErr_code("store_id_not_exist");
            result.setErr_msg("store_id不存在");
            return result;
        }

        //ORDER_PAYCODE_UNDEFIND
        String[] payCodeList = new String[]{"01","02"};

        for (Iterator iter = payItemList.iterator(); iter.hasNext();) {
            PayItem payItem = (PayItem) iter.next();
            String tmpPayCode = payItem.getPay_code();
            if (Arrays.asList(payCodeList).contains(tmpPayCode)) {
                result.setErr_code("order_paycode_undefind");
                result.setErr_msg("支付方式编码未定义");
                return result;
            }
        }

        result.setSuccess(true);
        return result;
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 生成商品查询签名
     */
    @PostMapping("/getCommodityQuerySign")
    public String getCommodityQuerySign(@RequestBody CommodityQueryRequest commodityQueryRequest) throws MiyaApiException {
        System.out.println(commodityQueryRequest.toString());
        return MiyaSignature.rsaSign(commodityQueryRequest.initSignContent(), appPrivateKey, commodityQueryRequest.getCharset(), commodityQueryRequest.getSign_type());
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 生成促销计算签名
     */
    @PostMapping("/getPromoteCalcSign")
    public String getPromoteCalcSign(@RequestBody PromoteCalcRequest promoteCalcRequest) throws MiyaApiException{
        String signContent = promoteCalcRequest.initSignContent();
        return MiyaSignature.rsaSign(signContent, appPrivateKey, promoteCalcRequest.getCharset(), promoteCalcRequest.getSign_type());
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 生成会员查询签名
     */
    @PostMapping("/getMemberQuerySign")
    public String getMemberQuerySign(@RequestBody MemberQueryRequest memberQueryRequest) throws MiyaApiException{
        return MiyaSignature.rsaSign(memberQueryRequest.initSignContent(), appPrivateKey, memberQueryRequest.getCharset(), memberQueryRequest.getSign_type());
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 生成获取订单号小票号签名
     */
    @PostMapping("/getTicketQuerySign")
    public String getTicketQuerySign(@RequestBody TicketQueryRequest ticketQueryRequest) throws MiyaApiException{
        return MiyaSignature.rsaSign(ticketQueryRequest.initSignContent(), appPrivateKey, ticketQueryRequest.getCharset(), ticketQueryRequest.getSign_type());
    }

    /**
     * @author zhangminglei
     * @params
     * @return
     * @createTime 2018/9/12
     * @desc 生成订单回调签名
     */
    @PostMapping("/getOrderWriteBackSign")
    public String getOrderWriteBackSign(@RequestBody OrderWriteBackRequest orderWriteBackRequest) throws MiyaApiException{
        return MiyaSignature.rsaSign(orderWriteBackRequest.initSignContent(), appPrivateKey, orderWriteBackRequest.getCharset(), orderWriteBackRequest.getSign_type());
    }
}